var express = require('express');
var datafile_conf = require('../config').filedata;
var router = express.Router();
const fileUpload = require('express-fileupload');
router.use(fileUpload({
    limits: { fileSize: datafile_conf.size_limit},
}));
const { exec } = require('child_process');
const path = require("path");

// 文件上传接口
router.post('/upload', async function (req, res) {
    try {
        if (!req.files || Object.keys(req.files).length === 0) {
            return res.send(
                {
                "errno": 1, // 只要不等于 0 就行
                "message": "No files were uploaded."
            });
        }

        filename_ext = path.extname(req.files.file.name);
        let file_name = req.files.file.md5 + filename_ext;
        let dir = datafile_conf.local_dir + file_name.slice(0, 2) + "/"
        exec("mkdir -p " + dir, (error, stdio, stderr) => {
            if (error) {
                return res.send(
                    {
                        "errno": 1, // 只要不等于 0 就行
                        "message": "create dir failed."
                    });
            }
            req.files.file.mv(dir + file_name, (error, data) => {
                if (error) {
                    return res.send(
                        {
                            "errno": 1, // 只要不等于 0 就行
                            "message": "mv file failed."
                        });
                }
                return res.send({
                    "errno": 0, // 注意：值是数字，不能是字符串
                    "data": {
                        "fileUrl": datafile_conf.host + datafile_conf.url + file_name.slice(0, 2) + "/" + file_name, // 图片 src ，必须
                        "alt": "yyy", // 图片描述文字，非必须
                        "href": "zzz" // 图片的链接，非必须
                    }
                });
            });
        });

    }
    catch (err) {
        return res.send(
            {
                "errno": 1, // 只要不等于 0 就行
                "message": err
            }
        )
    }
    //或者使用回调来处理
    /*
    file.mv(dest + file.name, function (err) {
        if (err) { upload res.status(500).send(err); }
        res.json({ ok: true, message: 'OK' });
    });*/
});
module.exports = router;
